﻿using lwzlz.Application.Information;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace lwzlz.Application.Model
{
    public class DataBaseDal
    {
        private string conn = ConfigurationManager.ConnectionStrings["CMS"].ToString();
        private static DataBaseDal _instance;
        //public static string conn = SqlHelper.GetSessionString("sqlstring").ToString();
        public static DataBaseDal GetInstance()
        {
            return _instance ?? (_instance = new DataBaseDal());
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        public IList<DataBaseInfo> GetList()
        {
            var s = "Initial Catalog=";
            int first = conn.IndexOf("Initial Catalog=") + s.Length;
            int last = conn.IndexOf("Data Source=") - 1;
            int count = last - first;
            string Catalog = conn.Substring(first, count);

            var strSql = new StringBuilder(10);
            strSql.Append("use master;");
            strSql.AppendFormat("SELECT Name FROM sys.databases where Name='{0}';", Catalog);
            //DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.GetSessionString("sqlstring").ToString(), CommandType.Text, strSql.ToString());//?不用sqlhelper
            DataSet ds1 = null;
            SqlConnection connstring = null;  //SqlClient数据库连接方式
            //OleDbConnection connole = null;   //oledb数据库连接方式
            //if (conn.Contains("Provider"))
            //{
            //    connole = new OleDbConnection(conn);
            //}
            //else
            //{
            //}
            connstring = new SqlConnection(_instance.conn);
            SqlCommand cmd = new SqlCommand(strSql.ToString(), connstring);
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                ds1 = new DataSet();

                // Fill the DataSet using default values for DataTable names, etc
                da.Fill(ds1);
                connstring.Close();
            }
            var list = new List<DataBaseInfo>();
            if (Utils.HasMoreRow(ds1))
            {
                list.AddRange(from DataRow dr in ds1.Tables[0].Rows select DataRowToModel(dr));
            }
            return list;
        }

        /// <summary>
        /// 转换实体
        /// </summary>
        /// <param name="row">数据行</param>
        /// <returns></returns>
        private DataBaseInfo DataRowToModel(DataRow row)
        {
            var model = new DataBaseInfo();
            if (row != null)
            {
                if (!string.IsNullOrEmpty(row["Name"].ToString()))
                {
                    model.Name = row["Name"].ToString();
                }
            }
            return model;
        }
    }
}